﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ReturnBusiness : BaseBusiness<PB_Return>, IPB_ReturnBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_ReturnBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_Return>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_Return>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Return, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            where = where.And(x => _operator.Property.DeptIds.Contains(x.DetpId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_Return> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_Return data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_Return data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 回货单选择收货方
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_Department>> GetReturnDeptListDataAsync()
        {
            var listdata = Db.GetIQueryable<Base_Department>();
            return await listdata.ToListAsync();
        }

        /// <summary>
        /// 根据项目获取物料信息
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        public async Task<List<ViewPB_ReturnDTO>> GetReturnListDataAsync(string ProjectId)
        {
            string sqlMain = @"select *,(EstimatedQuantity-alreadyReturnNums) as Difference from (select ROW_NUMBER() over(ORDER BY `Code` ) rn,a.Id,`Code`,`Name`,Spec,CONVERT(SUM(IFNULL(EstimatedQuantity,0)), UNSIGNED INTEGER) as EstimatedQuantity,CONVERT(IFNULL(b.ReturnNums,0),UNSIGNED INTEGER) as alreadyReturnNums,'0' as ReturnNums from View_InvoiceDetailed as a left join PB_ReturnDetailLog as b on a.ProjectId=b.ProjectId and a.Id=b.MaterialId  where a.ProjectId='" + ProjectId + "' group by a.Id,`Code`,`Name`,Spec,b.ReturnNums ) as t";
            List<ViewPB_ReturnDTO> listdata = await Db.GetListBySqlAsync<ViewPB_ReturnDTO>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }


        /// <summary>
        /// PDA根据项目获取物料信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<List<ViewPB_ReturnDTO>> GetPDAReturnListDataAsync(ReturnCondition data)
        {
            //通过项目楼号获取回货数据
            string sqlMain = "select * FROM( SELECT PB_PickUpList.Id, PB_PickUpList.`Name`,PB_PickUpList.BuildingNumberID,PB_PickUpList.`Code`,PB_PickUpList.ProjectId DesignId,IFNULL( PB_PickUpList.IssuedQuantity, 0 ) EstimatedQuantity,IFNULL( ReturnData.ReturnNums, 0 ) alreadyReturnNums FROM( SELECT a.MaterialId AS Id,c.Id ParentId,c.BuildingNumberID,PB_Material.`Code`,PB_Material.`Name`,PB_Material.Spec,c.ProjectId,IFNULL( sum( a.PackNums ), 0 ) IssuedQuantity FROM PB_TransportBillDetail AS a LEFT JOIN PB_PickUpMain AS uplist ON a.PreparationNoteId = uplist.Id LEFT JOIN PB_Material ON a.MaterialId = PB_Material.Id  LEFT JOIN PB_DeliveryNoticeItem AS item ON uplist.ParentId = item.Id LEFT JOIN PB_DesignList AS c ON item.DesignId = c.Id  WHERE c.BuildingNumberID = '" + data.BuildingId+"'  AND c.ProjectId='"+data.ProjectId+"' GROUP BY a.MaterialId,c.Id,c.ProjectId,c.BuildingNumberID ) AS PB_PickUpList LEFT JOIN (SELECT IFNULL( Sum( returnss.ThisReturnNums ), 0 ) AS ReturnNums,returnss.BuildingId,returnss.MaterialId FROM PB_Return AS log LEFT JOIN PB_ReturnDetailLog AS returnss ON returnss.ParentId = log.Id WHERE returnss.BuildingId = '"+data.BuildingId+"'AND returnss.ProjectId='"+data.ProjectId+ "'  GROUP BY	returnss.BuildingId,	returnss.MaterialId ) AS ReturnData ON ReturnData.MaterialId = PB_PickUpList.ID  WHERE PB_PickUpList.IssuedQuantity > 0 	) AS o {0} ";
            string Code = "";
            if (!data.Keyword.IsNullOrEmpty())
            {
                Code =$" 	WHERE	o.Name LIKE '%{data.Keyword}%'  OR o.Code LIKE '%{data.Keyword}%' ";
            }
            sqlMain = string.Format(sqlMain, Code);
            List<ViewPB_ReturnDTO> listdata = await Db.GetListBySqlAsync<ViewPB_ReturnDTO>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                //对于老单子进行处理,已发数量取值为设计清单设计数量
                StringBuilder sqldesignList = new StringBuilder();
   
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" OK.`MaterialCode` ' Code',");
                sqldesignList.AppendLine(" OK.MaterialName 'Name',");
                sqldesignList.AppendLine(" OK.MaterialId 'Id',");
                sqldesignList.AppendLine("OK.Spec 'Spec',");
                sqldesignList.AppendLine(" IFNULL(OK.RealNums, 0) EstimatedQuantity,");
                sqldesignList.AppendLine(" IFNULL(ReturnData.ReturnNums, 0) alreadyReturnNums");
                sqldesignList.AppendLine(" FROM");
                sqldesignList.AppendLine(" (");
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" SUM(Nums) AS 'Nums',");
                sqldesignList.AppendLine(" SUM(RealNums) AS 'RealNums',");
                sqldesignList.AppendLine(" ParentId AS 'ParentId',");
                sqldesignList.AppendLine(" MaterialId AS 'MaterialId',");
                sqldesignList.AppendLine(" MaterialName AS 'MaterialName',");
                sqldesignList.AppendLine(" MaterialCode AS 'MaterialCode',");
                sqldesignList.AppendLine(" BuildingNumber AS 'BuildingNumber',");
                sqldesignList.AppendLine(" buildingID AS 'buildingID',");
                sqldesignList.AppendLine(" Spec AS 'Spec'");
                sqldesignList.AppendLine(" FROM");
                sqldesignList.AppendLine(" (");
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" building.Buildingnumber BuildingNumber,");
                sqldesignList.AppendLine(" building.Id buildingID,");
                sqldesignList.AppendLine(" M.`Name` MaterialName,");
                sqldesignList.AppendLine(" M.`Code` MaterialCode,");
                sqldesignList.AppendLine(" M.Spec Spec,");
                sqldesignList.AppendLine(" a.ParentId,");
                sqldesignList.AppendLine(" a.MaterialId AS MaterialId,");
                sqldesignList.AppendLine(" a.Nums,");
                sqldesignList.AppendLine(" a.Slot,");
                sqldesignList.AppendLine(" a.RealNums,");
                sqldesignList.AppendLine(" a.State,");
                sqldesignList.AppendLine(" a.Id AS SubId");
                sqldesignList.AppendLine(" FROM");
                sqldesignList.AppendLine(" PB_DesignDetail AS a");
                sqldesignList.AppendLine(" LEFT JOIN PB_DesignList AS List ON a.ParentId = List.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Material AS M ON a.MaterialId = M.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Buildingnumber AS building ON List.BuildingNumberID = building.Id");
                sqldesignList.AppendLine(" WHERE");
                sqldesignList.AppendLine(" a.State = 0");
                sqldesignList.AppendLine(" AND List.ProjectId = '"+data.ProjectId+"'");
                sqldesignList.AppendLine(" AND List.BuildingNumberID = '"+data.BuildingId+"' UNION ALL");
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" building.Buildingnumber AS 'BuildingNumber',");
                sqldesignList.AppendLine(" building.Id buildingID,");
                sqldesignList.AppendLine(" M.`Name` MaterialName,");
                sqldesignList.AppendLine(" M.`Code` MaterialCode,");
                sqldesignList.AppendLine(" M.Spec Spec,");
                sqldesignList.AppendLine(" a.ParentId,");
                sqldesignList.AppendLine(" a.MaterialId AS MaterialId,");
                sqldesignList.AppendLine(" a.Nums,");
                sqldesignList.AppendLine(" a.Slot,");
                sqldesignList.AppendLine(" a.RealNums,");
                sqldesignList.AppendLine(" a.State,");
                sqldesignList.AppendLine(" a.Id AS SubId");
                sqldesignList.AppendLine(" FROM");
                sqldesignList.AppendLine(" PB_DesignDetail AS a");
                sqldesignList.AppendLine(" LEFT JOIN PB_DesignList AS List ON a.ParentId = List.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Material AS M ON a.MaterialId = M.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Buildingnumber AS building ON List.BuildingNumberID = building.Id");
                sqldesignList.AppendLine(" WHERE");
                sqldesignList.AppendLine(" State = 1");
                sqldesignList.AppendLine(" AND List.ProjectId = '"+data.ProjectId+"'");
                sqldesignList.AppendLine(" AND List.BuildingNumberID = '"+data.BuildingId+"' UNION ALL");
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" building.Buildingnumber AS 'BuildingNumber',");
                sqldesignList.AppendLine(" building.Id buildingID,");
                sqldesignList.AppendLine(" M.`Name` MaterialName,");
                sqldesignList.AppendLine(" M.`Code` MaterialCode,");
                sqldesignList.AppendLine(" M.Spec Spec,");
                sqldesignList.AppendLine(" a.ParentId,");
                sqldesignList.AppendLine(" a.MaterialId AS MaterialId,");
                sqldesignList.AppendLine(" (-a.Nums) AS Nums,");
                sqldesignList.AppendLine(" a.Slot,");
                sqldesignList.AppendLine(" (-a.RealNums) AS RealNums,");
                sqldesignList.AppendLine(" a.State,");
                sqldesignList.AppendLine(" a.Id AS SubId");
                sqldesignList.AppendLine(" FROM");
                sqldesignList.AppendLine(" PB_DesignDetail AS a");
                sqldesignList.AppendLine(" LEFT JOIN PB_DesignList AS List ON a.ParentId = List.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Material AS M ON a.MaterialId = M.Id");
                sqldesignList.AppendLine(" LEFT JOIN PB_Buildingnumber AS building ON List.BuildingNumberID = building.Id");
                sqldesignList.AppendLine(" WHERE");
                sqldesignList.AppendLine(" a.State = 2");
                sqldesignList.AppendLine(" AND List.ProjectId = '"+data.ProjectId+"'");
                sqldesignList.AppendLine(" AND List.BuildingNumberID = '"+data.BuildingId+"'");
                sqldesignList.AppendLine(" ) AS k");
                sqldesignList.AppendLine(" GROUP BY");
                sqldesignList.AppendLine(" MaterialId,");
                sqldesignList.AppendLine(" ParentId,");
                sqldesignList.AppendLine(" MaterialName,");
                sqldesignList.AppendLine(" BuildingNumber,");
                sqldesignList.AppendLine(" MaterialCode,");
                sqldesignList.AppendLine(" buildingID,");
                sqldesignList.AppendLine(" Spec");
                sqldesignList.AppendLine(" ORDER BY");
                sqldesignList.AppendLine(" BuildingNumber,");
                sqldesignList.AppendLine(" MaterialCode");
                sqldesignList.AppendLine(" ) AS OK");
                sqldesignList.AppendLine(" LEFT JOIN(");
                sqldesignList.AppendLine(" SELECT");
                sqldesignList.AppendLine(" IFNULL(Sum(returnss.ThisReturnNums ), 0 ) AS ReturnNums,");
                sqldesignList.AppendLine("returnss.BuildingId,");
                sqldesignList.AppendLine("returnss.MaterialId");
                sqldesignList.AppendLine("FROM");
                sqldesignList.AppendLine("PB_Return AS log");
                sqldesignList.AppendLine("LEFT JOIN PB_ReturnDetailLog AS returnss ON returnss.ParentId = log.Id");
                sqldesignList.AppendLine("WHERE");
                sqldesignList.AppendLine("returnss.BuildingId = '"+data.BuildingId+"'");
                sqldesignList.AppendLine("GROUP BY");
                sqldesignList.AppendLine("returnss.BuildingId,");
                sqldesignList.AppendLine("returnss.MaterialId");
                sqldesignList.AppendLine(") AS ReturnData ON ReturnData.MaterialId = OK.MaterialId");
                if (!data.Keyword.IsNullOrEmpty()) {
                    sqldesignList.AppendLine("WHERE OK.Name LIKE '%{data.Keyword}%'  OR OK.Code LIKE '%{data.Keyword}%'");
                }
                List<ViewPB_ReturnDTO> listDesignList =await Db.GetListBySqlAsync<ViewPB_ReturnDTO>(sqldesignList.ToString());
                return listDesignList;
            }
        }


/// <summary>
/// 回货单保存
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[Transactional]
        public async Task SaveReturnDataAsync(PB_ReturnDTO data)
        {
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (data.Id.IsNullOrEmpty())
            {
                PB_Return pbdata = new PB_Return();
                string pid = IdHelper.GetId();
                pbdata.Id = pid;
                pbdata.ParentId = data.ParentId;
                pbdata.DetpId = bdata.DepartmentId;
                pbdata.ReturnDate = data.ReturnDate;
                pbdata.Consignee = data.Consignee;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreatorRealName = bdata.RealName;
                pbdata.Remarks = data.Remarks;
                pbdata.State = 0;
                pbdata.CreateTime = DateTime.Now;
                pbdata.Deleted = false;
                pbdata.StorId = data.StorId;
                List<PB_ReturnDetailLog> logdata = new List<PB_ReturnDetailLog>();
                foreach (var item in data.ReturnDetail)
                {
                    PB_ReturnDetailLog logdetail = new PB_ReturnDetailLog();
                    logdetail.Id = IdHelper.GetId();
                    logdetail.ParentId = pid;
                    logdetail.ProjectId = data.ParentId;
                    logdetail.MaterialId = item.Id;
                    logdetail.MaterialCode = item.Code;
                    logdetail.MaterialName = item.Name;
                    logdetail.MaterialSpec = item.Spec;
                    logdetail.DeliverNums = item.EstimatedQuantity;
                    logdetail.ReturnNums = item.ReturnNums;
                    logdetail.Remarks = item.Remarks;
                    logdetail.SortingSum = 0;
                    logdetail.CreatorId = _operator.UserId;
                    logdetail.CreatorRealName = bdata.RealName;
                    logdetail.CreateTime = DateTime.Now;
                    logdetail.Deleted = false;
                    logdetail.ThisReturnNums = item.ThisReturnNums;

                    logdata.Add(logdetail);
                }
                List<PB_ReturnDetailImg> listimg = new List<PB_ReturnDetailImg>();
                if (listimg.Count >= 1)
                {
                    foreach (var item in data.Imgs)
                    {
                        PB_ReturnDetailImg imgdata = new PB_ReturnDetailImg();
                        imgdata.Id = IdHelper.GetId();
                        imgdata.ParentId = pid;
                        imgdata.img = item;
                        imgdata.CreatorId = _operator.UserId;
                        imgdata.CreatorRealName = bdata.RealName;
                        imgdata.CreateTime = DateTime.Now;
                        imgdata.Deleted = false;
                        listimg.Add(imgdata);
                    }
                     //保存图片信息
                await Db.InsertAsync(listimg);
                }


                //保存回货单
                await Db.InsertAsync<PB_Return>(pbdata);

                //保存回货单明细表
                await Db.InsertAsync(logdata);
               
               
               
            }
            else
            {
                await ExecuteSqlAsync("delete FROM PB_ReturnDetailLog where ParentId='" + data.Id + "'");

                List<PB_ReturnDetailLog> logdata = new List<PB_ReturnDetailLog>();
                foreach (var item in data.ReturnDetail)
                {
                    PB_ReturnDetailLog logdetail = new PB_ReturnDetailLog();
                    logdetail.Id = IdHelper.GetId();
                    logdetail.ParentId = data.Id;
                    logdetail.ProjectId = data.ParentId;
                    logdetail.MaterialId = item.Id;
                    logdetail.MaterialCode = item.Code;
                    logdetail.MaterialName = item.Name;
                    logdetail.MaterialSpec = item.Spec;
                    logdetail.DeliverNums = item.EstimatedQuantity;
                    logdetail.ReturnNums = item.ReturnNums;
                    logdetail.Remarks = item.Remarks;
                    logdetail.CreatorId = _operator.UserId;
                    logdetail.CreatorRealName = bdata.RealName;
                    logdetail.CreateTime = DateTime.Now;
                    logdetail.Deleted = false;
                    logdetail.ThisReturnNums = item.ThisReturnNums;
                    logdata.Add(logdetail);
                }
                //保存回货单明细表
                await Db.InsertAsync(logdata);
            }
        }

        /// <summary>
        /// 回货单审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Transactional]
        public async Task ToExamineReturnDataAsync(string id)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
            string rid = IdHelper.GetId();
            string qrcode = h_TdRe + "," + rid;
            string sqlstr = "update PB_Return set State=1 where Id='" + id + "';";
            //sqlstr += "insert into TD_Receiving (Id,StorId,Code,OrderTime,RecTime,Type,RefCode,Status,TotalNum,InNum,TotalAmt,Remarks,CreateTime,CreatorId,Deleted,QrCode)select '"+ rid + "', StorId, '" + sjtime + "', NOW(), NOW(), 'Return', id, 0, IFNULL((SELECT sum(ReturnNums) from PB_ReturnDetailLog  where ParentId = '" + id + "'), 0),0,0,Remarks,NOW(),'" + _operator.UserId + "',0,'" + qrcode + "' from PB_Return where id = '" + id + "'; ";
            //sqlstr += "INSERT into TD_RecDetail (Id ,RecId ,StorId  ,MaterialId  ,PlanNum ,RecNum ,InNum ,CreateTime ,CreatorId ,Deleted,price,amount)SELECT UUID_SHORT(),'" + rid + "',(select StorId from PB_Return where id='" + id + "' ),MaterialId,ReturnNums,0,0,NOW(),'" + _operator.UserId + "',0,0,0 from PB_ReturnDetailLog where ParentId='" + id + "' and ReturnNums!=0;";

            await ExecuteSqlAsync(sqlstr);
        }

        /// <summary>
        /// 获取回货单list
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_ReturnListDTO>> GetDataListDataAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_Return, PB_Project, Base_Department, Base_Department, PB_TransportBill, PB_ReturnListDTO>> select = (a, b, c, d, e) => new PB_ReturnListDTO
            {
                ProjectName = b.Name,
                ConsigneeName = c.Name,
                StorName = d.Name,
                TrainNumber = e.TrainNumber,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on a.StorId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_TransportBill>() on a.BillId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            if (!input.Search.Keyword.IsNullOrEmpty())
            {
                var keyword = input.Search.Keyword.Trim();
                q = q.Where(x => x.ProjectName.Contains(keyword) || x.ConsigneeName.Contains(keyword));
            }
            return await q.GetPageResultAsync(input);
        }

        /// <summary>
        /// 查看回货单详细信息
        /// </summary>
        /// <param name="Id">回货单Id</param>
        /// <returns></returns>
        public async Task<PB_ReturnDataDTO> GetReturnDataAsync(string Id)
        {
            Expression<Func<PB_Return, PB_Project, Base_Department, PB_ReturnDataDTO>> select = (a, b, c) => new PB_ReturnDataDTO
            {
                ProjectName = b.Name,
                ConsigneeName = c.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var qdata = await q.Where(x => x.Id == Id).FirstOrDefaultAsync();
            string sqlMain = @"select m.`Name`,m.Spec, b.*,IFNULL(b.ReturnNums,0) as alreadyReturnNums,'0' as SortingNums from PB_Return as a INNER join PB_ReturnDetailLog as b on a.Id=b.ParentId 
LEFT JOIN PB_Material as m on b.MaterialId=m.Id
where a.Id='"+Id+"'";
            qdata.ReturnDetail = await Db.GetListBySqlAsync<PB_ReturnDetailLogDTO>(sqlMain);
            qdata.Imgs = await Db.GetIQueryable<PB_ReturnDetailImg>().Where(x => x.ParentId == qdata.Id).ToListAsync();
            if (qdata != null)
            {
                return qdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 获取回货分拣单list
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_ReturnListDTO>> GetDataSortingListDataAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_Return, PB_Project, Base_Department, PB_ReturnListDTO>> select = (a, b, c) => new PB_ReturnListDTO
            {
                ProjectName = b.Name,
                ConsigneeName = c.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.ProjectName, keyword)
                      || EF.Functions.Like(x.ConsigneeName, keyword));
            }
            q = q.Where(x => _operator.Property.DeptIds.Contains(x.DetpId) && x.State != 0);
            return await q.GetPageResultAsync(input);
        }

        /// <summary>
        /// 回货单分拣保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SaveReturnSortingDataAsync(PB_ReturnSortingDataDTO data)
        {
            var q = await Db.GetIQueryable<PB_ReturnDetail>().Where(x => x.ProjectId == data.ParentId).ToListAsync();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_ReturnDetail> listdata = new List<PB_ReturnDetail>();
            List<PB_ReturnDetailList> ldata = new List<PB_ReturnDetailList>();
            foreach (var item in data.ReturnDetail)
            {
                PB_ReturnDetail pbdata = new PB_ReturnDetail();
                pbdata.Id = IdHelper.GetId();
                pbdata.ProjectId = data.ParentId;
                pbdata.MaterialId = item.MaterialId;
                pbdata.MaterialCode = item.MaterialCode;
                pbdata.MaterialName = item.MaterialName;
                pbdata.MaterialSpec = item.MaterialSpec;
                pbdata.DeliverNums = item.DeliverNums;
                pbdata.ReturnNums = item.SortingNums;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreatorRealName = bdata.RealName;
                pbdata.CreateTime = DateTime.Now;
                pbdata.Deleted = false;
                pbdata.Remarks = item.Remarks;
                listdata.Add(pbdata);
                PB_ReturnDetailList pdata = new PB_ReturnDetailList();
                pdata.Id = IdHelper.GetId();
                pdata.ParentId = item.Id;
                pdata.ProjectId = data.ParentId;
                pdata.MaterialId = item.MaterialId;
                pdata.MaterialCode = item.MaterialCode;
                pdata.MaterialName = item.MaterialName;
                pdata.MaterialSpec = item.MaterialSpec;
                pdata.DeliverNums = item.DeliverNums;
                pdata.ReturnNums = item.SortingNums;
                pdata.CreatorId = _operator.UserId;
                pdata.CreatorRealName = bdata.RealName;
                pdata.CreateTime = DateTime.Now;
                pdata.Deleted = false;
                pdata.Remarks = item.Remarks;
                ldata.Add(pdata);
            }
            await Db.InsertAsync(ldata);
            if (q.Count == 0)
            {
                await Db.InsertAsync(listdata);
            }
            else
            {
                string sqlMain = string.Empty;
                foreach (var item in data.ReturnDetail)
                {
                    sqlMain += " update PB_ReturnDetail set ReturnNums=IFNULL(ReturnNums,0)+" + item.SortingNums + " where ProjectId='" + data.ParentId + "' and MaterialId='" + item.MaterialId + "'; ";
                }
                await ExecuteSqlAsync(sqlMain);
            }


            //朱柏清 2022-1-11 修改回货单状态，并生成入库单
            //foreach (var item in data.ReturnDetail)
            //{
            //    var materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.StorId == item. && x.LocalId == item.LocalId).FirstOrDefaultAsync();
            //    if (materdata == null)
            //    {
            //        //不存在新增
            //        IT_LocalMaterial itdata = new IT_LocalMaterial();
            //        itdata.Id = IdHelper.GetId();
            //        itdata.MaterialId = item.MaterialId;
            //        itdata.StorId = item.StorId;
            //        itdata.LocalId = item.LocalId;
            //        itdata.Nums_N = item.Num;
            //        itdata.CreatorId = _operator.UserId;
            //        itdata.CreateTime = DateTime.Now;
            //        itdata.Deleted = false;
            //        itdata.ScanNum = item.Num;
            //        itdata.CheckNum = 0;
            //        await Db.InsertAsync<IT_LocalMaterial>(itdata);
            //    }
            //    else
            //    {
            //        //存在修改
            //        string sqlMain = @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Num + ",ScanNum=IFNULL(ScanNum,0)+" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';update PB_Material set CheckNum=IFNULL(CheckNum,0)+" + item.Num + ", ScanNum=IFNULL(ScanNum,0)+" + item.Num + " where Id='" + item.MaterialId + "'";
            //        await ExecuteSqlAsync(sqlMain);
            //    }
            //    //库存明细表
            //    IT_LocalDetail detdata = new IT_LocalDetail();
            //    detdata.Id = IdHelper.GetId();
            //    detdata.StorId = item.StorId;
            //    detdata.LocalId = item.LocalId;
            //    detdata.MaterialId = item.MaterialId;
            //    // detdata.MeasureId = Materialdata.storageId;
            //    detdata.InTime = DateTime.Now;
            //    detdata.CreateTime = DateTime.Now;
            //    detdata.CreatorId = _operator.UserId;
            //    detdata.Deleted = false;
            //    detdata.Num = item.Num;
            //    //detdata.BarCode = data.packqrcode;
            //    // detdata.PackId = packId;
            //    detdata.OldOrNew = 1;
            //    await Db.InsertAsync<IT_LocalDetail>(detdata);

            //    //插入库存明细表
            //    PB_StockLog lodata = new PB_StockLog();
            //    lodata.Id = IdHelper.GetId();
            //    //  lodata.PackId = packId;
            //    lodata.StorId = item.StorId;
            //    lodata.LocationId = item.LocalId;
            //    lodata.StockNumber = item.Num;
            //    lodata.CreatorId = _operator.UserId;
            //    lodata.CreatorName = bdata.RealName;
            //    lodata.OperatorId = _operator.UserId;
            //    lodata.OrderID = item.InStorId;
            //    lodata.CreateTime = DateTime.Now;
            //    lodata.Type = 2;
            //    lodata.State = 0;
            //    lodata.OldOrNew = 1;
            //    await Db.InsertAsync<PB_StockLog>(lodata);
            //}
            string sql = @"update PB_Return set State=2 where Id='" + data.Id + "'";
            await ExecuteSqlAsync(sql);

            //查询本次回货是否完成，完成修改回货单状态
            //Expression<Func<PB_ReturnDetailLog, PB_ReturnDetailList, PB_ReturnListDataDTO>> select = (a, b) => new PB_ReturnListDataDTO
            //{
            //    Nums = b.ReturnNums
            //};
            //select = select.BuildExtendSelectExpre();
            //var qd = from a in Db.GetIQueryable<PB_ReturnDetailLog>().AsExpandable()
            //        join b in Db.GetIQueryable<PB_ReturnDetailList>() on a.Id equals b.ParentId into ab
            //        from b in ab.DefaultIfEmpty()
            //        select @select.Invoke(a, b);
            //var qdata = await qd.Where(x => x.ParentId == data.Id).ToListAsync();
            //var list = qdata.GroupBy(x => new { x.ParentId, x.MaterialId, x.ReturnNums }).Select(x => new { ParentId = x.Key.ParentId, MaterialId = x.Key.MaterialId, ReturnNums = x.Key.ReturnNums, Nums = x.Sum(i => i.Nums) });
            //if (list.Count() > 0)
            //{
            //    int indexnums = 0;
            //    foreach (var item in list)
            //    {
            //        if (item.ReturnNums == item.Nums)
            //        {
            //            if (indexnums != 2)
            //            {
            //                indexnums = 1;
            //            }
            //        }
            //        else
            //        {
            //            indexnums = 2;
            //        }
            //    }
            //    if (indexnums == 1)
            //    {
            //        string sql = @"update PB_Return set State=2 where Id='" + data.Id + "'";
            //        await ExecuteSqlAsync(sql);
            //    }
            //}
        }

        /// <summary>
        /// 回货单分拣详细信息
        /// </summary>
        /// <param name="Id">回货单Id</param>
        /// <returns></returns>
        public async Task<PB_ReturnDataDTO> GetReturnSortingDataAsync(string Id)
        {
            Expression<Func<PB_Return, PB_Project, Base_Department, PB_ReturnDataDTO>> select = (a, b, c) => new PB_ReturnDataDTO
            {
                ProjectName = b.Name,
                ConsigneeName = c.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var qdata = await q.Where(x => x.Id == Id).FirstOrDefaultAsync();
            string sqlMain = @"select b.*,IFNULL(b.ReturnNums,0) as alreadyReturnNums,'0' as SortingNums,(b.ReturnNums-(SELECT CONVERT(IFNULL(SUM(ReturnNums),0), UNSIGNED INTEGER) FROM PB_ReturnDetailList WHERE ParentId=b.Id and ProjectId=a.ParentId and MaterialId=b.MaterialId)) as Nums from PB_Return as a left join PB_ReturnDetailLog as b on a.Id=b.ParentId left join PB_ReturnDetail as c on a.ParentId=c.ProjectId and b.MaterialId=c.MaterialId where a.Id='" + qdata.Id + "'";
            qdata.ReturnDetail = await Db.GetListBySqlAsync<PB_ReturnDetailLogDTO>(sqlMain);
            qdata.Imgs = await Db.GetIQueryable<PB_ReturnDetailImg>().Where(x => x.ParentId == qdata.Id).ToListAsync();
            if (qdata != null)
            {
                return qdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// PDA回货单保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SavePDAReturnDataAsync(PB_ReturnDTO data)
        {
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            var PB_DeliveryNotice = await Db.GetIQueryable<PB_DeliveryNotice>().Where(m=>m.Id==data.Id).FirstOrDefaultAsync();
            PB_Return pbdata = new PB_Return();
            string pid = IdHelper.GetId();
            pbdata.Id = pid;
            pbdata.ParentId = data.ParentId;
            pbdata.DetpId = bdata.DepartmentId;
            pbdata.ReturnDate = PB_DeliveryNotice.IssueDate;
            pbdata.Consignee = bdata.DepartmentId;
            pbdata.CreatorId = _operator.UserId;
            pbdata.CreatorRealName = bdata.RealName;
            pbdata.Remarks = PB_DeliveryNotice.Abstract;
            pbdata.State = 0;
            pbdata.CreateTime = DateTime.Now;
            pbdata.Deleted = false;
            pbdata.StorId = PB_DeliveryNotice.Address;
            pbdata.BillId = data.BillId;
            pbdata.NoticeId = data.Id;
            pbdata.BuildingId = data.BuildingId;
            pbdata.QrCode = "26," + pid;
            List<PB_ReturnDetailLog> logdata = new List<PB_ReturnDetailLog>();
            foreach (var item in data.PDAReturnDetail)
            {
                var DB = await Db.GetIQueryable<PB_ReturnDetailLog>().Where(m=>m.ParentId==data.Id&&m.MaterialId==item.Id&&m.BuildingId==data.BuildingId).FirstOrDefaultAsync();
                //if (DB!=null) {
                 //   String Update = "UPDATE   PB_ReturnDetailLog SET ReturnNums=ReturnNums+"+item.ReturnNums+ ",ThisReturnNums="+item.ReturnNums+" WHERE  Id='" + DB.Id+"'";
                   // await ExecuteSqlAsync(Update);
                //}
                //else {
                   // ViewPB_ReturnDTO qdata = data.PDAReturnDetail.Find(x => x.Id == item.Id);
                  //  if (qdata != null)
                    {
                        //item.ReturnNums = qdata.ReturnNums;
                    //}
                    PB_ReturnDetailLog logdetail = new PB_ReturnDetailLog();
                    string rdlid = IdHelper.GetId();
                    logdetail.Id = rdlid;
                    logdetail.ParentId =pid;
                    logdetail.ProjectId = data.ParentId;
                    logdetail.MaterialId = item.Id;
                    logdetail.MaterialCode = item.Code;
                    logdetail.MaterialName = item.Name;
                    logdetail.DeliverNums = item.EstimatedQuantity;
                    logdetail.MaterialSpec = item.Spec;
                    logdetail.ReturnNums = item.ReturnNums;
                    logdetail.Remarks = item.Remarks;
                    logdetail.CreatorId = _operator.UserId;
                    logdetail.CreatorRealName = bdata.RealName;
                    logdetail.CreateTime = DateTime.Now;
                    logdetail.Deleted = false;
                    logdetail.QrCode = Returnee + "," + rdlid;
                    logdetail.ThisReturnNums = item.ReturnNums;
                    logdetail.BuildingId = data.BuildingId;
                    logdata.Add(logdetail);
                }


               
            }

            //保存回货单明细表
            await Db.InsertAsync<PB_ReturnDetailLog>(logdata);
            //保存回货单
            await Db.InsertAsync<PB_Return>(pbdata);
        }

        /// <summary>
        /// 回货单选择收货仓库
        /// </summary>
        /// <param name="deptid">收货方ID</param>
        /// <returns></returns>
        /// 
        public async Task<List<Base_Department>> GetReturnWarehouseListDataAsync(string deptid)
        {
            var listdata = Db.GetIQueryable<Base_Department>().Where(x => x.ParentId == deptid && x.Type == 2);
            return await listdata.ToListAsync();
        }

        /// <summary>
        /// 获取收货人对应的收货单信息
        /// </summary>
        /// <param name="userqecode">人员二维码</param>
        /// <returns></returns>
        public async Task<List<PB_DeliveryNotice>> GetUserReturnDataAsync(string userqecode)
        {
            string userid = userqecode.Split(',')?[1].ToString();
            var pbdata = await Db.GetIQueryable<PB_DeliveryNotice>().Where(x => x.ConsigneeId == userid && x.AuditStatus == 1 && x.Type == 2).ToListAsync();

            return pbdata;
        }

        public async Task<PB_ReturnDataDTO> GetReturnSortingData(string Qrcode)
        {
            if (!string.IsNullOrEmpty(Qrcode))
            {
                string[] qrcodemodel = Qrcode.Split(',');
                string juber = qrcodemodel[0].ToString();
                if (juber == "26")
                {
                    Expression<Func<PB_Return, PB_Project, Base_Department, PB_ReturnDataDTO>> select = (a, b, c) => new PB_ReturnDataDTO
                    {
                        ProjectName = b.Name,
                        ConsigneeName = c.Name
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                            from c in ac.DefaultIfEmpty()
                            select @select.Invoke(a, b, c);
                    var qdata = await q.Where(x => x.Id == qrcodemodel[1]).FirstOrDefaultAsync();
                    string sqlMain = @"
SELECT  PP.* ,OO.num Nums  FROM (
select b.*,
a.Id AId,
b.ReturnNums AS alreadyReturnNums,
b.MaterialId AS PPMaterialId
FROM
	PB_Return AS a
	LEFT JOIN PB_ReturnDetailLog AS b ON a.Id = b.ParentId
	LEFT JOIN PB_ReturnDetail AS c ON a.ParentId = c.ProjectId 
	AND b.MaterialId = c.MaterialId WHERE a.Id = '"+qdata.Id+"') AS PP LEFT JOIN (select IFNULL(SUM(b.SortingSum),0) num,a.ParentId,b.MaterialId from PB_ReturnSorting  as a LEFT JOIN PB_ReturnSortDetail AS b ON b.ParentId=a.Id GROUP BY a.ParentId,MaterialId ) AS  OO ON  OO.ParentId=PP.AId  AND  OO.MaterialId=PP.PPMaterialId";
                    qdata.ReturnDetail = await Db.GetListBySqlAsync<PB_ReturnDetailLogDTO>(sqlMain);
                    qdata.Imgs = await Db.GetIQueryable<PB_ReturnDetailImg>().Where(x => x.ParentId == qdata.Id).ToListAsync();
                    if (qdata != null)
                    {
                        return qdata;
                    }
                    else
                    {
                        throw new BusException("暂无数据");
                    }
                }
                else if (juber == "27")
                {
                    var qdata = new PB_ReturnDataDTO();
                    string sqlMain = @"select b.*,IFNULL(c.ReturnNums,0) as alreadyReturnNums,'0' as SortingNums from PB_Return as a left join PB_ReturnDetailLog as b on a.Id=b.ParentId left join PB_ReturnDetail as c on a.ParentId=c.ProjectId and b.MaterialId=c.MaterialId where b.Id='" + qrcodemodel[1] + "'";
                    Expression<Func<PB_Return, PB_Project, Base_Department,PB_ReturnDetailLog, PB_ReturnDataDTO>> select = (a, b, c,d) => new PB_ReturnDataDTO
                    {
                        ProjectName = b.Name,
                        ConsigneeName = c.Name
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_Return>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Project>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                            from c in ac.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_ReturnDetailLog>() on a.Id equals d.ParentId into ad
                            from d in ad.DefaultIfEmpty()
                            select @select.Invoke(a, b, c,d);
                    PB_ReturnDetailLog aa =await Db.GetIQueryable<PB_ReturnDetailLog>().Where(m=>m.Id== qrcodemodel[1]).FirstOrDefaultAsync();
                    qdata = await q.Where(x => x.Id ==aa.ParentId).FirstOrDefaultAsync();
                    qdata.ReturnDetail = await Db.GetListBySqlAsync<PB_ReturnDetailLogDTO>(sqlMain);
                    qdata.Imgs = await Db.GetIQueryable<PB_ReturnDetailImg>().Where(x => x.ParentId == qdata.Id).ToListAsync();
                    if (qdata != null)
                    {
                        return qdata;
                    }
                    else
                    {
                        throw new BusException("暂无数据");
                    }
                }
                else
                {
                    throw new BusException("请求二维码类型有误");
                }
            }
            else
            {
                throw new BusException("请求二维码不可为空");
            }

        }
        /// <summary>
        /// 回货分拣确认生成收货单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddReceivingDataAsync(PB_RevingAdd data)
        {
            DateTime dt = new DateTime();
            Base_User RellName = await Db.GetIQueryable<Base_User>().Where(m => m.Id == _operator.UserId).FirstOrDefaultAsync();
            //创建收货单编号
            String RevingId = IdHelper.GetId();
            TD_Receiving Maindata = new TD_Receiving();
            Maindata.Id = RevingId;
            Maindata.StorId = data.StorId;
            //生成收货code
            Maindata.Code = RevingId;
            Maindata.OrderTime = DateTime.Now;
            Maindata.Type = "ReturnReceipt";//类型暂写死回货收回类型
            Maindata.RefCode = data.RefCode;
            Maindata.Status = 0;
            Maindata.SupId = "";//供应商
            Maindata.OrderId = data.OrderId;
            foreach (var item in data.Subdata) {
                Maindata.TotalNum += item.RecNum;
            }
           
            Maindata.InNum = 0;//入库数量默认为0
            Maindata.TotalAmt = data.TotalAmt;
            Maindata.Remarks = "";
            Maindata.ConfirmUserId = "";//确认人
            Maindata.AuditUserId = "";
            Maindata.CreateTime = DateTime.Now;
            Maindata.CreatorId = RellName.Id;
            Maindata.Deleted = false;
            Maindata.QrCode = h_TdRe + "," + RevingId;
            Maindata.CusID = "";
            Maindata.DeptId = RellName.DepartmentId;
            Maindata.RecTime = DateTime.Now;
            Maindata.UpdateTime = DateTime.Now;
            //插入收货单
            await Db.InsertAsync<TD_Receiving>(Maindata);
            List<TD_RecDetail> SubData = new List<TD_RecDetail>();
            foreach (var item in data.Subdata) {
                String SubId = IdHelper.GetId();
                TD_RecDetail tD_RecDetail = new TD_RecDetail();
                tD_RecDetail.Id = SubId;
                tD_RecDetail.RecId = RevingId;
                tD_RecDetail.StorId = data.StorId;
                tD_RecDetail.MaterialId = item.MaterialId;
                tD_RecDetail.MeasureId = "";
              
                tD_RecDetail.Price =item.Price;
                tD_RecDetail.PlanNum = item.PlanNum;
                tD_RecDetail.RecNum = item.RecNum;
                tD_RecDetail.InNum = 0;
                tD_RecDetail.Amount = item.Amount;
                tD_RecDetail.CreateTime = DateTime.Now;
                tD_RecDetail.CreatorId = RellName.Id;
                tD_RecDetail.Deleted = false;
                tD_RecDetail.TaskId = "";
                tD_RecDetail.TaxRate = 1;
                SubData.Add(tD_RecDetail);

            }
            await Db.InsertAsync<TD_RecDetail>(SubData);
        }

        /// <summary>
        /// 多个分拣单生成收货单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task AddBatchSorting(BatchSorting data)
        {
            Base_User RellName = await Db.GetIQueryable<Base_User>().Where(m => m.Id == _operator.UserId).FirstOrDefaultAsync();
            //获取分拣单号
            String RefCode = String.Join(",", data.ReturnSortingList);
            //收货单id
            string RecId = IdHelper.GetId();
            //创建收货明细
            List<TD_RecDetail> tD_RecDetails = new List<TD_RecDetail>();
            List<PB_ReturnSortDetail> pB_ReturnSortDetails = new List<PB_ReturnSortDetail>();
            for (int i=0;i<data.ReturnSortingList.Count;i++) {
                var list =await Db.GetIQueryable<PB_ReturnSortDetail>().Where(m=>m.ParentId==data.ReturnSortingList[i]).ToListAsync();
                if (list.Count>0) {
                    foreach (var item in list) {
                        pB_ReturnSortDetails.Add(item);
                    }
                }
            }
            //多个分拣单合并物料汇总
            var listDetail = pB_ReturnSortDetails.GroupBy(x => new {  x.MaterialId, }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.SortingSum) }).ToList();
           //收货主表总数
            double? nums = 0;
            double AmountCount = 0;
            //创建收货单明细
            foreach (var detail in listDetail) {
                //创建收货单明细
                TD_RecDetail tD_RecDetail = new TD_RecDetail();
                tD_RecDetail.Id = IdHelper.GetId();
                tD_RecDetail.RecId = RecId;
                tD_RecDetail.StorId = data.StorId;
                tD_RecDetail.LocaId = "";
                tD_RecDetail.MaterialId = detail.MaterialId;
                tD_RecDetail.MeasureId = "";
                //获取物料信息
                var pb_mater =await Db.GetIQueryable<PB_Material>().Where(m=>m.Id==detail.MaterialId).FirstOrDefaultAsync();
                tD_RecDetail.Price =Convert.ToDouble(pb_mater.Price == null ? 0 : pb_mater.Price);
                tD_RecDetail.PlanNum = Convert.ToDouble(detail.Nums);
                tD_RecDetail.RecNum = Convert.ToDouble(detail.Nums);
                tD_RecDetail.InNum = 0;
                tD_RecDetail.Amount = Convert.ToDouble(detail.Nums) * tD_RecDetail.Price;
                AmountCount += tD_RecDetail.Amount;
                tD_RecDetail.CreateTime = DateTime.Now;
                tD_RecDetail.CreatorId = _operator.UserId;
                tD_RecDetail.Deleted = false;
                tD_RecDetail.TaskId = "";
                tD_RecDetail.TaxRate = 0;
                tD_RecDetail.CirBillId = "";
                nums += tD_RecDetail.RecNum;
                tD_RecDetails.Add(tD_RecDetail);
            }
            TD_Receiving tD_Receiving = new TD_Receiving();
            tD_Receiving.Id = RecId;
            tD_Receiving.StorId = data.StorId;
            tD_Receiving.Code = IdHelper.GetId();
            tD_Receiving.OrderTime = DateTime.Now;
            tD_Receiving.RecTime = DateTime.Now;
            tD_Receiving.Type = "ReturnReceipt";
            tD_Receiving.RefCode = RefCode;
            tD_Receiving.Status = 0;
            tD_Receiving.SupId = "";
            tD_Receiving.TotalNum = Convert.ToDouble(nums);
            tD_Receiving.InNum = 0;
            tD_Receiving.TotalAmt = AmountCount;
            tD_Receiving.Remarks = "";
            tD_Receiving.ConfirmUserId = null;
            tD_Receiving.ConfirmTime = null;
            tD_Receiving.AuditUserId = null;
            tD_Receiving.AuditeTime = null;
            tD_Receiving.CreateTime = DateTime.Now;
            tD_Receiving.CreatorId = _operator.UserId;
            tD_Receiving.Deleted = false;
            tD_Receiving.QrCode = "23," + RecId;
            tD_Receiving.CusID = null;
            tD_Receiving.DeptId = RellName.DepartmentId;
            tD_Receiving.UpdateTime = DateTime.Now;
            tD_Receiving.OrderId = null;
            tD_Receiving.ToReviewTime = null;
            tD_Receiving.ToReviewTime = null;
            tD_Receiving.ToReviewStatus = null;
            await Db.InsertAsync<TD_RecDetail>(tD_RecDetails);
            await Db.InsertAsync<TD_Receiving>(tD_Receiving);
            string sqlmian = string.Empty;
            sqlmian = @" UPDATE  PB_ReturnSorting  SET State=1 WHERE Id in ('" + string.Join("','", data.ReturnSortingList.ToArray()) + "'); ";
            await Db.ExecuteSqlAsync(sqlmian);
        }
        

        #endregion

        #region 私有成员

        #endregion
    }
}